<template>
  <div class="footer-box">
    <div class="footer">
      <a class="btn" :class="{ disabled: disabeld }" @click="agree()">
        {{ text }}
      </a>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    index: {
      type: Number,
      default: 0
    },
    second: {
      type: [String, Number],
      default: 15
    },
    btnText: {
      type: String,
      default: '同意签署'
    },
    isabled: { // 父组件控制按钮是否可点击
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      time: this.second,
      timer: null
    };
  },
  computed: {
    text() {
      if (this.time > 0) {
        return `${this.btnText}(${this.time}s)`;
      }
      return this.btnText;
    },
    disabeld() {
      return this.time > 0 || !this.isabled;
    }
  },
  mounted() {
    this.isabled && this.countdown();
  },
  methods: {
    start() {
      this.time = this.second;
      this.countdown();
    },
    stop() {
      this.time = 0;
      clearInterval(this.timer);
    },
    countdown() {
      this.timer = setInterval(() => {
        if (this.time > 0) {
          this.time--;
        } else {
          this.stop();
        }
      }, 1000);
    },
    agree() {
      if (this.disabeld) {
        return false;
      }
      // 同意签署
      this.$emit('agree');
    }
  },
  watch: {
    index() {
      // vue-router切换时，停止当前定时器
      this.stop();
      this.isabled && this.start();
    },
    isabled() {
      this.isabled && this.start();
    }
  },
  beforeDestroy() {
    this.stop();
  }
};
</script>
<style lang="less" scoped>
.footer-box{
  height: 44px;
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 5;
  text-align: center;
  background: linear-gradient(
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 1) 20%
  );
  .btn {
    width: 375px;
    height: 44px;
    line-height: 44px;
    font-size: 17px;
    color: #ffffff;
    text-align: center;
    background: #00aaff;
    box-shadow: 0 4px 14px 0 rgba(199, 206, 210, 0.4);
    display: inline-block;
    &.disabled {
      background: #999;
    }
  }
}
</style>
